//
//  TDGiftAnimationView.m
//  钟剑飞
//
//  Created by 钟剑飞 on 2017/4/21.
//  Copyright © 2017年 tuandai. All rights reserved.
//

#import "TDGiftAnimationView.h"
#import "TDGiftAnimationCell.h"
#import "TCMsgHandler.h"

@interface TDGiftAnimationView ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *giftView;
@property (nonatomic, strong) NSTimer *timer;
// 新加进来的数据（当前需要处理的数据）
@property (nonatomic, strong) NSMutableArray *dataSource;
// 缓存未处理的数据
@property (nonatomic, strong) NSMutableArray * cacheData;
// 上次处理过的数据
@property (nonatomic, strong) NSMutableArray * storageData;
// 移除的礼物数据
@property (nonatomic, strong) NSMutableIndexSet* removeData;
@end

#define MAX_CELL 2
static NSString *cellID = @"GiftAnimationCellID";
@implementation TDGiftAnimationView

-(void)awakeFromNib {
    [super awakeFromNib];
    [self initNature];
}

- (void)initNature {
    [self.giftView registerClass:[TDGiftAnimationCell class] forCellReuseIdentifier:cellID];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(update) userInfo:nil repeats:YES];
}

- (void)update {
    //更新数据
    for (int i = 0;i < self.dataSource.count;i++) {
        IMUserAble *data = [self.dataSource objectAtIndex:i];
        data.live -= 0.1;
        if (data.live <= 0.0) {
            // 设置可连击时长
            data.live = 10;
            [self.removeData addIndex:i];
        }
    }
    if (self.removeData.count > 0) {
        if (self.removeData.count > self.cacheData.count) {
            NSIndexSet* deleteSet = [self.removeData indexesPassingTest:^BOOL(NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx >= self.cacheData.count) return YES;
                return NO;
            }];
            
            NSIndexSet* updateSet = [self.removeData indexesPassingTest:^BOOL(NSUInteger idx, BOOL * _Nonnull stop) {
                if (idx < self.cacheData.count) return YES;
                return NO;
            }];
            if (updateSet.count > 0) {
                // 将当前处理的数据变更为上次处理
                [self.storageData addObjectsFromArray:[self.dataSource objectsAtIndexes:updateSet]];
                // 把缓存的数据替换成当前需要处理的数据
                [self.dataSource replaceObjectsAtIndexes:updateSet withObjects:self.cacheData];
                // 移除缓存数据
                [self.cacheData removeObjectsAtIndexes:updateSet];
                [updateSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
                    IMUserAble * IMUserAble = self.dataSource[idx];
                    if(IMUserAble.giftBlock) IMUserAble.giftBlock();
                    [self.giftView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:IMUserAble.isLeftAnimation];
                }];
            }
            if (deleteSet.count > 0) {
                [self.storageData addObjectsFromArray:[self.dataSource objectsAtIndexes:deleteSet]];
                [deleteSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
                    IMUserAble * IMUserAble = self.dataSource[idx];
                    if(IMUserAble.giftBlock) IMUserAble.giftBlock();
                }];
                
                [self.dataSource removeObjectsAtIndexes:deleteSet];
                [self.giftView deleteRowsAtIndexPaths:[self converIndexPath:0 with:deleteSet] withRowAnimation:UITableViewRowAnimationFade];
            }
        } else {
            // 先取出上次处理完的数据
            [self.storageData addObjectsFromArray:[self.dataSource objectsAtIndexes:self.removeData]];
            // 从缓存起来的数据取出移除的数组来添加到当前的数组处理
            NSArray * array = [self.cacheData objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.removeData.count)]];
            [self.dataSource replaceObjectsAtIndexes:self.removeData withObjects:array];
            
            [self.removeData enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
                IMUserAble * IMUserAble = self.dataSource[idx];
                if(IMUserAble.giftBlock) IMUserAble.giftBlock();
                [self.giftView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:idx inSection:0]] withRowAnimation:IMUserAble.isLeftAnimation];
            }];
            // 把做完处理后的数据从缓存数组移除
            [self.cacheData removeObjectsInArray:array];
        }
        [self.removeData removeAllIndexes];
    }
    
    //更新storageData里的数据
    NSMutableIndexSet * indexSet = [NSMutableIndexSet new];
    for (int i = 0;i < self.storageData.count;i++) {
        IMUserAble * data = [self.storageData objectAtIndex:i];
        data.live -= 0.1;
        if (data.live <= 0.0) {
            [indexSet addIndex:i];
        }
    }
    if (indexSet.count > 0) {
        [self.storageData removeObjectsAtIndexes:indexSet];
    }
    
}


- (NSArray *)converIndexPath:(NSInteger)section with:(NSIndexSet*)set {
    NSMutableArray * array = [NSMutableArray new];
    [set enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
        [array addObject:[NSIndexPath indexPathForRow:idx inSection:section]];
    }];
    return array;
}


-(void)closeRoom {
    [self.timer invalidate];
    self.timer = nil;
}



-(void)addGift:(IMUserAble*)giftModel {
    BOOL isExist = NO;
    // 遍历数组是否发的是同一个礼物
    for (int i = 0; i < self.dataSource.count; ++i) {
        IMUserAble *data = self.dataSource[i];
        if ([data.giftID isEqualToString:giftModel.giftID] && [data.giftType isEqualToString:giftModel.giftType]) {
            [data resetLive];
            isExist = YES;
            return;
        }
    }

    // 检查上次处理的数据数组是否还有数据
    for (int i = 0; i < self.storageData.count; ++i) {
        IMUserAble *data = self.storageData[i];
        if ([data.giftID isEqualToString:giftModel.giftID] && [data.giftType isEqualToString:giftModel.giftType]) {
            [data resetLive];
            data.isComboed = YES;
            giftModel = data;
            [self.storageData removeObject:data];
        }
    }
    
    if (!isExist) {
        if (self.dataSource.count >= MAX_CELL) {
            for (IMUserAble *data in self.cacheData) {
                if ([data.giftID isEqualToString:giftModel.giftID] && [data.giftType isEqualToString:giftModel.giftType]) {
                    isExist = YES;
                    [data resetLive];
                }
            }
            [self.cacheData addObject:giftModel];
        }else {
            [self.dataSource insertObject:giftModel atIndex:0];
            UITableViewRowAnimation isLeftAnimation = giftModel.isLeftAnimation;
            if (isLeftAnimation != UITableViewRowAnimationLeft) {
                isLeftAnimation = UITableViewRowAnimationRight;
            }
            [self.giftView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:isLeftAnimation];
        }
    }

    
    
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TDGiftAnimationCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    cell.giftModel = self.dataSource[indexPath.item];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}


#pragma mark - 懒加载
-(UITableView *)giftView {
    if (!_giftView) {
        _giftView = [UITableView new];
        _giftView.dataSource = self;
        _giftView.delegate = self;
        [self addSubview:_giftView];
        
        [_giftView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
        
    }
    return _giftView;
}


-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

-(NSMutableArray *)cacheData {
    if (!_cacheData) {
        _cacheData = [NSMutableArray array];
    }
    return _cacheData;
}

-(NSMutableArray *)storageData {
    if (!_storageData) {
        _storageData = [NSMutableArray array];
    }
    return _storageData;
}

-(NSMutableIndexSet *)removeData {
    if (!_removeData) {
        _removeData = [NSMutableIndexSet new];
    }
    return _removeData;
}

@end
